package com.gxwgy.wg2404.bank.web;

import com.gxwgy.wg2404.bank.exceptions.MoneyNoEnoughException;
import com.gxwgy.wg2404.bank.service.AccountService;
import com.gxwgy.wg2404.bank.service.impl.AccountServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author 姚相国
 * @version 2.0
 * @className AccountServlet
 * @date 2024/10/13 16:40
 * 此类是改造Mvc下的demo项目，采用Mvc思想
 * 负责调度其他组件来完成任务
 */
@WebServlet("/transfer")
public class AccountServlet extends HttpServlet {

    // 调用业务实现类处理业务（调用Model处理业务）
    private AccountService accountService = new AccountServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 接收数据
        String fromAccount = request.getParameter("fromAccount");
        String toAccount = request.getParameter("toAccount");
        double money = Double.parseDouble(request.getParameter("money"));
        try {
            // 执行到这里说明成功
            accountService.transfer(fromAccount, toAccount,money);

            // 展示处理结果（View页面展示）
            response.sendRedirect(request.getContextPath() + "/success.jsp");

        } catch (MoneyNoEnoughException e) {
            // 执行到这里就失败（余额不足导致的）

            // 展示处理结果（View页面展示）
            response.sendRedirect(request.getContextPath() + "/moneynotenough.jsp");

        } catch (Exception e) {
            //执行到这里说明失败了

            // 展示处理结果（View页面展示）
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }
}
